/**
 * 处理和用户相关的数据
 * */
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserAPI, getUserDetailById, loginAPI } from '@/api/user'
const state = {
  token: getToken() || '', // 用户token
  userInfo: {}
}

const mutations = {
  // 存token
  setTokenMutations(state, val) {
    state.token = val
    setToken(state.token)
  },
  // 删除token
  removeTokenMutations(state) {
    state.token = ''
    removeToken()
  },
  // 设置用户信息
  setUserInfoMutations(state, val) {
    state.userInfo = val
  },
  // 删除用户信息
  removeUserInfoMutations(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登陆请求
  async loginActions(store, data) {
    const res = await loginAPI(data)
    store.commit('setTokenMutations', res.data)
  },
  // 用户信息
  async getUserInfoActions(store) {
    const res = await getUserAPI()
    const userDetailRes = await getUserDetailById(res.data.userId)
    store.commit('setUserInfoMutations', { ...res.data, ...userDetailRes.data })
    console.log(store.state.userInfo)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

